package com.yint.core;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public abstract class AbsSocketReactor extends AbsReactor {

	@Override
	protected final void handle() throws IOException {
		Set<SelectionKey> selectionKeys= onReact();
		if(selectionKeys!=null && selectionKeys.size()>0) {
			Iterator<SelectionKey> it = selectionKeys.iterator();
			SelectionKey key =null;
			while (it.hasNext()) {
				key=it.next();
				it.remove();
				dispatch(key);
			}
		}
	}
	
	/**
	 * 进行NIO事件选择
	 * 
	 * @return
	 * @throws IOException
	 */
	protected Set<SelectionKey> onReact() throws IOException {
		Selector selector = getSelector();
		if (selector == null) {
			throw new IOException("Channel Selector is null");
		}
		if (selector.select() == 0) {
			return null;
		}
		return selector.selectedKeys();
	}

	/**
	 * NIO 事件分发
	 * 
	 * @param handler
	 * @param selectedKey
	 * @throws IOException
	 */
	protected abstract void dispatch(SelectionKey selectedKey) throws IOException ;
	
	protected abstract Selector getSelector();
}
